package reflect;

import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MyReflect {

    public static void main(String[] args) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Student stu3 = new Student(12, "tom");

        //获取class 对象的三种方式,都可以
        //Class stu = Class.forName("reflect.Student");
        //Class stu = Student.class;
        Class stu = stu3.getClass();


        Field[] fs = stu.getDeclaredFields();
        for (Field f : fs) {
            System.out.println(f.getName());
            //获取字段类型
            Class ft = f.getType();
            System.out.println(ft.getName());

        }

        Method[] md = stu.getDeclaredMethods();
        for (Method m : md) {
            System.out.println(m.getName());
        }

        //无参构造器的new方法
        Object newStuInstance = stu.newInstance();
        System.out.println(newStuInstance);
        //注意类型一致
        Constructor newStuWithParams = stu.getConstructor(int.class, String.class);
        Object stu4WithParams = (Student) newStuWithParams.newInstance(21, "tom");
        System.out.println(stu4WithParams);
        //调用指定方法
        Method m = stu.getMethod("study");
        //只要传入一个实例就可以
        m.invoke(stu3);
        m.invoke(newStuInstance);
        m.invoke(stu4WithParams);

    }


}
